package com.elves.auth.config;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.util.concurrent.ThreadPoolExecutor;

@Configuration
@Slf4j
@EnableAsync
@Component
public class ThreadPoolConfig {

    @Resource
    AppConfig appConfig;

    @Bean(name = "${app.pool.name}")
    public ThreadPoolTaskExecutor elvesThreadPoolTaskExecutor() {
        AppConfig.Pool threadPoolConfig = appConfig.getPool();
        log.info("ThreadPoolTaskExecutor BeanName:{}", threadPoolConfig.getName());
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setBeanName(threadPoolConfig.getName());
        executor.setCorePoolSize(threadPoolConfig.getCorePoolSize()); // 核心线程数
        executor.setMaxPoolSize(threadPoolConfig.getMaxPoolSize()); // 最大线程数
        executor.setQueueCapacity(threadPoolConfig.getQueueCapacity()); // 队列容量
        executor.setKeepAliveSeconds(threadPoolConfig.getKeepAliveSeconds()); // 线程存活时间
        executor.setThreadNamePrefix(threadPoolConfig.getThreadPrefix()); // 线程名前缀
        // 策略配置，待完善
        log.warn("Do not set RejectedExecutionHandler: {}", threadPoolConfig.getRejectedExecutionHandler());
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); // 拒绝策略,CallerRunsPolicy，当线程和队列都满了，由发起线程的主线程自己执行
        executor.initialize(); // 初始化线程池
        log.info("ThreadPoolTaskExecutor ThreadNamePrefix: {}", executor.getThreadNamePrefix());
        return executor;
    }

}